package com.bosssoft.trainee.nontax.config.security.handler;/*
登录认证成功处理器类
@author shencanting
@date 2022/06/172152
**/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bosssoft.trainee.nontax.config.redis.RedisService;
import com.bosssoft.trainee.nontax.entity.po.UserPO;
import com.bosssoft.trainee.nontax.utils.JwtUtils;
import com.bosssoft.trainee.nontax.utils.LoginResult;
import com.bosssoft.trainee.nontax.utils.ResultCode;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException, ServletException {
        // 设置响应的编码格式
        response.setContentType("application/json;charset=UTF-8");
        //获取当登录用户信息
        UserPO userPO = (UserPO) authentication.getPrincipal();
        // 生成token
        String token = jwtUtils.generateToken(userPO);
        //设置token签名密钥及过期时间
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(token.replace("jwt_",""))
                .getBody().getExpiration().getTime();

        //创建登录结果对象
        LoginResult loginResult = new LoginResult(userPO.getId(), ResultCode.SUCCESS,token,expireTime);
        // 转为JSON格式
        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        //保存token到Redis
        String tokenKey ="token_"+token;
        redisService.set(tokenKey,token,jwtUtils.getExpiration()/1000);
    }
}
